﻿$(document).ready(function () {
    // $('#jqxWidget').hide();
    
    $('#mainSplitter').jqxSplitter({
        width: '100%', height: '100%',
        theme: theme, panels: [{ size: '30%' }]
    });

    $("#barParams").jqxNavigationBar({
        width: '100%',
        height: CurrentHeigth(),
        sizeMode: 'fitAvailableHeight', theme: theme
    });

    $(window).resize(function() {
        $('#barParams').jqxNavigationBar({ height: CurrentHeigth() });
        $('#barParams').jqxNavigationBar('expandAt', 0);
    });
 
    $("#rangeDate").jqxDateTimeInput({
        width: 250, height: 25,
        theme: theme,
        selectionMode: 'range',
        culture: 'ru-RU',
        maxDate: new $.jqx._jqxDateTimeInput.getDateTime(new Date())
    });

    $('#ShowButton').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    $('#xlsExport').jqxButton({ width: '150px', theme: theme, heigh: 50 });
    $('#htmlExporter').jqxButton({ width: '100px', theme: theme, heigh: 50 });
    
    $.ajax({
        url: "/data/detailscar", dataType: "json", type: 'get',
        contentType: 'application/json; charset=UTF-8'
    }).done(function (data) {
        for (var key in data) {
            var curElem = data[key];
            curElem.Name = '<img class=\'' + curElem.Class + '\' /><span>' + curElem.Name + '</span>';
        }
        var source = {
            datatype: 'array',
            datafields: [
                { name: 'Id' },
                { name: 'ParentId' },
                { name: 'Name' }
            ],
            id: 'Id',
            localdata: data
        };
        // create data adapter.
        var carDataAdapter = new $.jqx.dataAdapter(source);
        // perform Data Binding.
        carDataAdapter.dataBind();
        var carRecords = carDataAdapter.getRecordsHierarchy('Id', 'ParentId', 'items', [{ name: 'Name', map: 'label' }, { name: 'Id', map: 'id' }]);
        $('#carTree').jqxTree({ source: carRecords, width: '100%', height: '99%', checkboxes: true, hasThreeStates: true, allowDrag: false, theme: theme });
        $('#barParams').jqxNavigationBar('expandAt', 0);
    });

    $.ajax({
        url: '/data/Classificator/20000000000',
        type: "GET",
        contentType: 'application/json; charset=UTF-8',
        success: function (data) {
            $("#mesuringTree").jqxTree({
                checkboxes: true, hasThreeStates: true, allowDrag: false, 
                width: '100%',heigh:'99%', theme: theme,
                source: data
            });
            $('#mesuringTree').bind('expand', function (event) {
                var $element = $(event.args.element);
                var loader = false;
                var loaderItem = null;
                var children = $element.find('li');
                $.each(children, function () {
                    var item = $('#mesuringTree').jqxTree('getItem', this);
                    if (item.label == 'Loading...') {
                        loaderItem = item;
                        loader = true;
                        return false;
                    };
                });
                if (loader) {
                    $.ajax({
                        url: '/data/Classificator', dataType: "json",
                        data: { id: loaderItem.value },
                        contentType: 'application/json; charset=UTF-8',
                        success: function (data) {
                            if (data.length > 0) {
                                $('#mesuringTree').jqxTree('addTo', data, $element[0]);
                                $('#mesuringTree').jqxTree('removeItem', loaderItem.element);
                            } else {
                                $('#mesuringTree').jqxTree('removeItem', loaderItem.element);
                            }
                        },
                        error: function () {
                            alert("Не удалось подключиться к серверу");
                        }
                    });
                }
            });
        },
        error: function () {
            alert('Невозможно подключиться к серверу данных.');
        }
    });

    $('#ShowButton').bind('click',function () {
        
        var sendData = new Object();
        sendData.MassiveId = new Array();
        
        var elemetns = $('#carTree').jqxTree('getItems');
        for (var key in elemetns) {
            var item = elemetns[key];
            if (item.id.indexOf('tree_') == -1&&item.checked) {
                sendData.MassiveId.push(item.id);
            }
        }
        
        sendData.MassiveMesuringId = new Array();

        elemetns = $('#mesuringTree').jqxTree('getItems');
        for (var key in elemetns) {
            var item = elemetns[key];
            if (item.hasItems == false) {
                if (item.checked&& item.label!='Loading...') {
                    sendData.MassiveMesuringId.push(item.id);
                }
            }
        }
       
        var selection = $("#rangeDate").jqxDateTimeInput('getRange');
        sendData.BTime = selection.from;
        sendData.ETime = selection.to;
        if (sendData.MassiveId.length == 0 || sendData.BTime==null||sendData.ETime==null) {
            alert('Проверьте, пожалуйста, исходные данные');
        } else {
            $("#mainGrid").jqxGrid('updatebounddata');
            $.ajax({
            url: "/data/ArchiveState/",
            type: "POST",
            cache: false,
            data: JSON.stringify(sendData),
            dataType: 'json',
            contentType: 'application/json; charset=utf-8',
            success: function (data) {
                //var data = JSON.stringify(data).toString();
                // prepare the data
                source.localdata = data;
                $("#mainGrid").jqxGrid('updatebounddata');
                //$('#jqxWidget').show();
                $(window).resize();
            },
            error: function () {
                alert('Проверьте исходные данные');
            }
        });
        }
        

    });

    var source = {
        datatype: "json",
        type: "POST",
        contentType: 'application/json; charset=UTF-8',
        datafields: [
            { name: 'CarId', type: 'int' },
            { name: 'CarName', type: 'text' },
            { name: 'TypeMesure' },
            { name: 'DefaultMesure' },
            { name: 'DateTimeOfMesure', type: 'date', cellsformat: 'ISO2' },
            { name: 'Value' }
        ]
    };
    var dataAdapter = new $.jqx.dataAdapter(source);
    $("#mainGrid").jqxGrid({
        width: "100%",
        height: '100%',
        columnsresize: true,
        theme:theme,
        source: dataAdapter,
        
        autoheight: false,
        pageable: false,
        groupable: true,
        sortable: true,
        filterable: true,

        groups: ['CarName', 'TypeMesure', 'DefaultMesure'],
        columns: [
            { text: 'Индификатор', datafield: 'CarId', width: 100 },
            { text: 'Тип машины', datafield: 'CarName' },
            { text: 'Тип измерения', datafield: 'TypeMesure' },
            { text: 'Измерение', datafield: 'DefaultMesure' },
            { text: 'Время', datafield: 'DateTimeOfMesure', width: 200 },
            { text: 'Значение', datafield: 'Value' }
        ]
    });

    $('#xlsExport').bind('click',function () {
        $("#mainGrid").jqxGrid('exportdata', 'xls', 'Отчет');
    });

    $('#htmlExporter').bind('click', function () {
        var q = $('#mainGrid').jqxGrid('getloadedrows');
        if (q.length > 0) {
            shapka = "<tr>";
            resultColumn = [];
            for (var VAR in $("#mainGrid").jqxGrid('columns').records) {
                var filed = $("#mainGrid").jqxGrid('columns').records[VAR].datafield;
                if (filed != null && filed != "") {
                    var needAdd = true;
                    for (var VAR2 in $("#mainGrid").jqxGrid('groups')) {
                        if ($("#mainGrid").jqxGrid('groups')[VAR2] == filed) {
                            needAdd = false;
                            break;
                        }
                    }
                    if (needAdd) {
                        shapka = shapka + "<td>" + $("#mainGrid").jqxGrid('columns').records[VAR].text + "</td>";
                        resultColumn.push(filed);
                    }

                }
            }
            shapka = shapka + "</tr>";
            result = '<center><table style="width:95%">';
            var temp = new Array();
            for (var VAR in q) {
                if (q[VAR].level == 0) {
                    temp.push(q[VAR]);
                }
            }
            if (temp.length > 0) {
                GetChildren(temp, 0);
            } else {
                result = result + shapka + RowTable(q);
            }
            result = result + '<\/table><\/center>';
            infoWind = window.open("", "Заголовок", "width=1000,height=800,menubar=yes,scrollbars=1");
            infoWind.document.writeln('<html><head><title>Версия для печати<\/title><\/head><body text="#000000" bgcolor="#FFFFFF">');
            infoWind.document.writeln('<form><input type="button" value="Печать" onClick="self.print()"></form>');
            infoWind.document.writeln(result);
            infoWind.document.writeln('<\/body><\/html>');
            infoWind.document.close();
            infoWind.focus();
        } else {
            alert('Нету элементов для отображения');
        }
    });

});


    var result = '';
    var resultColumn = [];
    var shapka = "";



    function GetChildren(data,level) {
        for (var VAR in data) {
            result = result + '<tr><td colspan="3"><h' + (level + 1).toString() + '>' + data[VAR].group + '</h' + (level + 1).toString() + '></td></tr>';
            if (data[VAR].subGroups.length > 0) {
                GetChildren(data[VAR].subGroups,level+1);
            } else {
                result = result + shapka+RowTable(data[VAR].subItems);
            }
        }
    }
        
    function RowTable(data) {
        var newRow = "";
        for (var VAR in data) {
            var cur = data[VAR];
            newRow = newRow + '<tr>';
            for (var VAR2 in resultColumn) {
                newRow = newRow + '<td>' + cur[resultColumn[VAR2]] + '</td>';
            }
            newRow = newRow + '</tr>';
        }
        return  newRow;
    }
